package com.flow.server.modules.process.model.controller;

import com.flow.server.common.response.CommonResponse;
import com.flow.server.modules.base.controller.BaseController;
import com.flow.server.modules.process.model.service.IModelRestService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：流程模型 前端控制器
 * <p>
 * 作者：Ostrich Hu
 * 时间：2020/1/17 16:09 星期五
 */
@Api(tags = "流程模型")
@RestController
@RequestMapping("api/rest/model")
public class ModelRestController extends BaseController {

    @Resource
    private IModelRestService iModelRestService;

    @ApiOperation(value = "分页查询流程模型")
    @GetMapping("/list/page")
    public CommonResponse getModelList(HttpServletRequest request) {
        Map<String, Object> result = iModelRestService.getModelList(request);
        return CommonResponse.ok(result);
    }

    @ApiOperation(value = "根据模型id查询流程xml")
    @GetMapping("/{modelId}/xml")
    public CommonResponse getModelXMl(@PathVariable String modelId) {
        byte[] modelEditorSource = repositoryService.getModelEditorSource(modelId);
        String xmlStr = new String(modelEditorSource, StandardCharsets.UTF_8);
        HashMap<String, String> map = Maps.newHashMap();
        map.put("xmlStr", xmlStr);
        return CommonResponse.ok(map);
    }

    @ApiOperation("根据流程实例id获取运行时流程图")
    @GetMapping("/img/{instanceId}")
    public void getWorkflowImage(HttpServletResponse response, @PathVariable String instanceId) {
        iModelRestService.getWorkflowImage(instanceId, response);
    }

    @ApiOperation(value = "根据模型id查询流程xml")
    @DeleteMapping("/del/{modelId}")
    public CommonResponse delModelById(@PathVariable String modelId) {
        iModelRestService.deleteById(modelId);
        return CommonResponse.ok();
    }

    @ApiOperation(value = "根据模型id部署模型")
    @PostMapping("/deploy/{modelId}")
    public CommonResponse deploymentModel(@PathVariable String modelId) {
        return iModelRestService.deploymentModel(modelId) ? CommonResponse.ok() : CommonResponse.error();

    }

    @ApiOperation(value = "保存流程模型")
    @PostMapping(value = "/save")
    public CommonResponse saveModel(HttpServletRequest request) {
        return iModelRestService.saveModel(request) ? CommonResponse.ok() : CommonResponse.error();
    }

    @ApiOperation(value = "编辑流程模型")
    @PutMapping(value = "/upd/{modelId}")
    public CommonResponse updateModel(HttpServletRequest request, @PathVariable String modelId) {
        return iModelRestService.updateModel(request, modelId) ? CommonResponse.ok() : CommonResponse.error();
    }

}
